package be.groept.ace.enquete.servlets;

import java.io.IOException;
import java.util.SortedSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.User;
import be.groept.ace.enquete.model.dao.DAOCommand;
import be.groept.ace.enquete.model.dao.DAOFactory;
import be.groept.ace.enquete.model.dao.DAOManager;
import be.groept.ace.enquete.model.exceptions.DAOException;

/**
 * Servlet implementation class AdminUsersServlet
 */
@WebServlet("/admin/users/*")
public class AdminUsersServlet extends AdminServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AdminUsersServlet.class);
	
	@Override
	protected int handleGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		setPage(request, "users");
		setTitle(request, "Beheer users");
		setNavigationSelectedLink(request, 2);
		addHeaderLink(request, 1, "Nieuw", response.encodeURL(request.getContextPath() + "/admin/user"));
		
		DAOManager daoManager = null;
		try {
			daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
		} catch (DAOException daoe) {
			logger.fatal(daoe.toString());
			throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
		}
		
		try {
			@SuppressWarnings("unchecked")
			SortedSet<User> users = (SortedSet<User>) daoManager.transactionAndClose(new DAOCommand() {
				
				@Override
				public Object execute(DAOManager daoManager) throws DAOException {
					return daoManager.getUserDAO().findAllUsers();
				}
			});
			
			request.setAttribute("users", users);
		} catch (DAOException e) {
			logger.error(e.toString());
			throw new ServletException(e.getMessage());
		}
		
		return 200;	
	}

	@Override
	protected int handlePost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		return 404;
	}

	
	

}
